package com.pai4j.pgc.service.aig;
import com.pai4j.domain.vo.llm.*;
import com.pai4j.pgc.controller.community.AibotSocket;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.util.List;

/**
 *
 *
 * @author: CYM-pai
 * @date: 2025/10/27 16:08
 **/
@Service
public class DeepSeekAIService {

    private static final String MODEL = "deepseek-chat";

    @Value("${deepseek.api-key:}")
    private String apiKey;

    public ChatCompletionResponse chat(List<ChatCompletionMessage> messageList) throws Exception {
        DeepSeekAIClient client = new DeepSeekAIClient(apiKey);
        final List<ChatCompletionMessage> messages = messageList;
        return client.ChatCompletion(new ChatCompletionRequest(
                MODEL,
                messages,
                320000,
                0.3f,
                1
        ));
    }

    public Flux<String> chatByStreamV3(List<ChatCompletionMessage> messageList) {
        try {
            return new DeepSeekAIClient(apiKey).
                    ChatCompletionStreamV3(new ChatCompletionRequest(
                            MODEL, messageList, 1000, 0.3f, 1));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void chat(SseEmitter emitter, List<ChatCompletionMessage> messageList) throws Exception {
        DeepSeekAIClient client = new DeepSeekAIClient(apiKey);
        final List<ChatCompletionMessage> messages = messageList;
        try {
            client.ChatCompletionStream(new ChatCompletionRequest(
                    MODEL,
                    messages,
                    1000,
                    0.3f,
                    1
            )).subscribe(
                    streamResponse -> {
                        if (streamResponse.getChoices().isEmpty()) {
                            return;
                        }
                        for (ChatCompletionStreamChoice choice : streamResponse.getChoices()) {
                            String finishReason = choice.getFinishReason();
                            if (finishReason != null) {
                                emitter.send("finished");
                                continue;
                            }
                            String responseContent = choice.getDelta().getContent();
                            if (responseContent.equals("```") || responseContent.equals("json") ) {
                                continue;
                            }
                            responseContent = responseContent.replaceAll("\n", "<br>");
                            System.out.println(responseContent);
                            emitter.send(responseContent);
                        }
                    },
                    error -> {
                        error.printStackTrace();
                    },
                    () -> {
//                        emitter.complete(); // 完成事件流发送
                    }
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void chatByWebSocket(String userId, List<ChatCompletionMessage> messageList) throws Exception {
        DeepSeekAIClient client = new DeepSeekAIClient(apiKey);
        final List<ChatCompletionMessage> messages = messageList;
        try {
            client.ChatCompletionStream(new ChatCompletionRequest(
                    MODEL,
                    messages,
                    1000,
                    0.3f,
                    1
            )).subscribe(
                    streamResponse -> {
                        if (streamResponse.getChoices().isEmpty()) {
                            return;
                        }
                        for (ChatCompletionStreamChoice choice : streamResponse.getChoices()) {
                            String finishReason = choice.getFinishReason();
                            if (finishReason != null) {
                                AibotSocket.doSend(userId, "finished");
                                continue;
                            }
                            String responseContent = choice.getDelta().getContent();
                            if (responseContent.equals("```") || responseContent.equals("json") ) {
                                continue;
                            }
                            responseContent = responseContent.replaceAll("\n", "<br>");
                            System.out.println(responseContent);
                            AibotSocket.doSend(userId, responseContent);
                        }
                    },
                    error -> {
                        error.printStackTrace();
                    },
                    () -> {
//                        emitter.complete(); // 完成事件流发送
                    }
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}